package com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPlanningPt.service.impl;


import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.zfzx.sjcj.common.excel.handler.ActiveFaultVerifyBaseHandler;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.analysis.vo.HddcAppZztCountVo;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningPt.repository.HddcGeologicalsvyplanningptRepository;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningPt.repository.entity.HddcGeologicalsvyplanningptEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPlanningPt.repository.HddcWyGeologicalsvyplanningptNativeRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPlanningPt.repository.HddcWyGeologicalsvyplanningptRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPlanningPt.repository.entity.HddcWyGeologicalsvyplanningptEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPlanningPt.service.HddcWyGeologicalsvyplanningptService;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPlanningPt.viewobjects.HddcWyGeologicalsvyplanningptQueryParams;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPlanningPt.viewobjects.HddcWyGeologicalsvyplanningptVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcWyGeologicalsvyplanningptServiceImpl implements HddcWyGeologicalsvyplanningptService {

    private final HddcWyGeologicalsvyplanningptRepository hddcWyGeologicalsvyplanningptRepository;
    private final HddcWyGeologicalsvyplanningptNativeRepository hddcWyGeologicalsvyplanningptNativeRepository;
    private final HddcGeologicalsvyplanningptRepository hddcGeologicalsvyplanningptRepository;
    private final ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler;

    @Autowired
    public HddcWyGeologicalsvyplanningptServiceImpl(HddcWyGeologicalsvyplanningptRepository hddcWyGeologicalsvyplanningptRepository,
                                                    HddcWyGeologicalsvyplanningptNativeRepository hddcWyGeologicalsvyplanningptNativeRepository,
                                                    HddcGeologicalsvyplanningptRepository hddcGeologicalsvyplanningptRepository,
                                                    ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler) {
        this.hddcWyGeologicalsvyplanningptRepository = hddcWyGeologicalsvyplanningptRepository;
        this.hddcWyGeologicalsvyplanningptNativeRepository = hddcWyGeologicalsvyplanningptNativeRepository;
        this.hddcGeologicalsvyplanningptRepository = hddcGeologicalsvyplanningptRepository;
        this.activeFaultVerifyBaseHandler = activeFaultVerifyBaseHandler;
    }

    @Override
    public JSONObject queryHddcWyGeologicalsvyplanningpts(HddcWyGeologicalsvyplanningptQueryParams queryParams, int curPage, int pageSize) {
        Page<HddcWyGeologicalsvyplanningptEntity> hddcWyGeologicalsvyplanningptPage =
                this.hddcWyGeologicalsvyplanningptNativeRepository.queryHddcWyGeologicalsvyplanningpts(queryParams, curPage, pageSize);
        return PlatformPageUtils.formatPageData(hddcWyGeologicalsvyplanningptPage);
    }


    @Override
    public HddcWyGeologicalsvyplanningptEntity getHddcWyGeologicalsvyplanningpt(String uuid) {
        return this.hddcWyGeologicalsvyplanningptRepository.findById(uuid).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeologicalsvyplanningptEntity saveHddcWyGeologicalsvyplanningpt(HddcWyGeologicalsvyplanningptEntity po) {
        String uuid = UUIDGenerator.getUUID();
        po.setUuid(uuid);
        if (StringUtils.isEmpty(po.getCreateUser())) {
            po.setCreateUser(PlatformSessionUtils.getUserId());
        }
        po.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        po.setIsValid(PlatformConstants.Y);

        HddcGeologicalsvyplanningptEntity hddcGeologicalsvyplanningptEntity = new HddcGeologicalsvyplanningptEntity();
        BeanUtils.copyProperties(po, hddcGeologicalsvyplanningptEntity);
        hddcGeologicalsvyplanningptEntity.setExtends4(po.getTown());
        hddcGeologicalsvyplanningptEntity.setExtends5(String.valueOf(po.getLon()));
        hddcGeologicalsvyplanningptEntity.setExtends6(String.valueOf(po.getLat()));
        this.hddcGeologicalsvyplanningptRepository.save(hddcGeologicalsvyplanningptEntity);
        this.hddcWyGeologicalsvyplanningptRepository.save(po);
        return po;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeologicalsvyplanningptEntity updateHddcWyGeologicalsvyplanningpt(HddcWyGeologicalsvyplanningptEntity hddcWyGeologicalsvyplanningpt) {
        Optional<HddcWyGeologicalsvyplanningptEntity> oldItemOptional = hddcWyGeologicalsvyplanningptRepository.findById(hddcWyGeologicalsvyplanningpt.getUuid());
        if (!oldItemOptional.isPresent())
            return new HddcWyGeologicalsvyplanningptEntity();
        HddcWyGeologicalsvyplanningptEntity entity = oldItemOptional.get();
        UpdateUtil.copyNullProperties(entity, hddcWyGeologicalsvyplanningpt);
        hddcWyGeologicalsvyplanningpt.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcWyGeologicalsvyplanningpt.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcWyGeologicalsvyplanningptRepository.save(hddcWyGeologicalsvyplanningpt);
        return hddcWyGeologicalsvyplanningpt;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcWyGeologicalsvyplanningpts(List<String> ids) {
        List<HddcWyGeologicalsvyplanningptEntity> entityList = this.hddcWyGeologicalsvyplanningptRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(entityList) && entityList.size() > 0) {
            this.hddcWyGeologicalsvyplanningptRepository.deleteAll(entityList);
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public BigInteger queryHddcWyGeologicalsvyplanningpt(HddcAppZztCountVo queryParams) {
        return hddcWyGeologicalsvyplanningptNativeRepository.queryHddcWyGeologicalsvyplanningpt(queryParams);
    }

    @Override
    public void exportFile(HddcAppZztCountVo queryParams, HttpServletResponse response) {
        List<HddcWyGeologicalsvyplanningptEntity> poList =
                hddcWyGeologicalsvyplanningptNativeRepository.exportGeoPoint(queryParams);
        List<HddcWyGeologicalsvyplanningptVO> list = new ArrayList<>();
        for (HddcWyGeologicalsvyplanningptEntity po : poList) {
            HddcWyGeologicalsvyplanningptVO vo = new HddcWyGeologicalsvyplanningptVO();
            BeanUtils.copyProperties(po, vo);
            list.add(vo);
        }
        EasyPoiExcelUtil.exportExcel(list, "地质调查规划点-点", "地质调查规划点-点",
                HddcWyGeologicalsvyplanningptVO.class, "地质调查规划点-点.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder msg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(activeFaultVerifyBaseHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcWyGeologicalsvyplanningptVO> result =
                    ExcelImportUtil.importExcelMore(file.getInputStream(), HddcWyGeologicalsvyplanningptVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcWyGeologicalsvyplanningptVO vo : result.getFailList())
                    msg.append("第").append(vo.getRowNum()).append("行").append(vo.getErrorMsg()).append("<br />");
                if (msg.length() > 0)
                    return msg.toString();
            }
            List<HddcWyGeologicalsvyplanningptVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return msg.append("成功导入").append(list.size()).append("条记录").toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcWyGeologicalsvyplanningptVO> voList) {
        for (HddcWyGeologicalsvyplanningptVO vo : voList) {
            HddcWyGeologicalsvyplanningptEntity po = new HddcWyGeologicalsvyplanningptEntity();
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(vo, po);
            saveHddcWyGeologicalsvyplanningpt(po);
        }
    }

    @Override
    public List<HddcWyGeologicalsvyplanningptEntity> findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(String userId, String taskId, String projectId, String isValid) {
        return hddcWyGeologicalsvyplanningptRepository.findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(userId, taskId, projectId, isValid);
    }

    @Override
    public List<HddcWyGeologicalsvyplanningptEntity> findAllByCreateUserAndIsValid(String userId, String isValid) {
        return hddcWyGeologicalsvyplanningptRepository.findAllByCreateUserAndIsValid(userId, isValid);
    }


    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcWyGeologicalsvyplanningptEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeologicalsvyplanningptRepository.queryHddcA1InvrgnhasmaterialtablesByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for (HddcWyGeologicalsvyplanningptEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeologicalsvyplanningptRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcWyGeologicalsvyplanningptEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeologicalsvyplanningptRepository.queryHddcA1InvrgnhasmaterialtablesByTaskId(taskId);
        if (!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for (HddcWyGeologicalsvyplanningptEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeologicalsvyplanningptRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }

    }


}
